<template>
	<view class="page-bg">
		<view class="page-form">
			<uni-forms :modelValue="formData" :label-width="100">
				<uni-forms-item label="商品图片(选填)">
					<uni-file-picker ref="filePicker" limit="1" style="color:grey" :del-icon="false" disable-preview
						:imageStyles="imageStyles" file-mediatype="image" @select="selectPic">
						<image :src="picServiceUrl+formData.show_image" class="img-pic" v-if="formData.show_image">
						</image>
						<view v-else>选择</view>
					</uni-file-picker>
				</uni-forms-item>
				<uni-forms-item label="商品名称" name="title">
					<uni-easyinput type="text" v-model="formData.title" maxlength="16" placeholder="请输入商品名称" />
				</uni-forms-item>

				<uni-forms-item label="分类" name="type">
					<view class="select-info" @click="typeOpen()">
						<view v-if="!typeIndex" class="podct">选择分类</view>
						<view v-else>{{typeRange[typeIndex].title}}</view>
						<image class="row" src="/static/image/row.png"></image>
					</view>
				</uni-forms-item>
				<uni-forms-item label="原价" name="original" v-show="normsIndex==null">
					<uni-easyinput type="digit" v-model="formData.original" placeholder="请输入原价" />
				</uni-forms-item>
				<uni-forms-item label="底价" name="price" v-show="normsIndex==null&&!memberDiscount">
					<uni-easyinput type="digit" v-model="formData.price" placeholder="请输入底价" />
				</uni-forms-item>

				<uni-forms-item label="商品规格" name="type" class="hide-pad">
					<view class="select-info" @click="openNorms()">
						<view v-if="normsIndex==null" class="podct">(选填)如分量、尺寸等</view>
						<view v-else>
							{{normsRange[normsIndex].title}}
						</view>
						<image class="row" src="/static/image/row.png"></image>
					</view>
				</uni-forms-item>
				<view class="guige-info" v-for="item,indx in normsRange[normsIndex].childs" :key="indx">
					<view v-if="item.checked">
						<view class="title">
							{{item.title}}
						</view>
						<view class="price-info">
							<view class="del" @click="delPriceType(indx)">
								<image src="/static/image/icon2/xx.png"></image>
							</view>
							<span>原价：</span><input type="digit" v-model="item.original" />
							<span v-show="!memberDiscount">底价：</span><input type="digit" v-show="!memberDiscount"
								v-model="item.price" />
							<span>库存：</span><input type="digit" placeholder="(选填)默认9999" v-model="item.repetory" />
						</view>
					</view>
				</view>


				<uni-forms-item label="商品属性" name="type" class="hide-pad">
					<view class="select-info" @click="openAttribute()">
						<view v-if="!checkedAttribute.length" class="podct">(选填)如冰度、辣度等</view>
						<view v-else>
							<span v-for="(item,index) in checkedAttribute" :key="index">
								<span v-if="index!=0">/</span>{{item.title}}
							</span>
						</view>
						<image class="row" src="/static/image/row.png"></image>
					</view>
				</uni-forms-item>
				<view v-for="(nix,index) in attributeRange" :key="index">
					<view class="guige-info" v-if="nix.checked">
						<view class="title">
							{{nix.title}}
						</view>
						<view class="price-info">
							<view class="del" @click="attributeChange(index)">
								<image src="/static/image/icon2/xx.png"></image>
							</view>
							<span v-for="item,indx in nix.childs" :key="indx">
								<span v-if="indx!=0">/</span><span v-if="item.checked">{{item.title}}</span>
							</span>
						</view>
					</view>
				</view>
			</uni-forms>
		</view>


		<view class="sub-bt-btn" v-if="crrGoods">
			<view class="left" @click="submitForm(0)">
				删除商品
			</view>
			<view class="right" @click="submitForm(1)">
				保存编辑
			</view>
		</view>
		<view class="sub-bt-btn" v-if="!crrGoods">
			<view class="left" @click="submitForm(2)">
				继续添加
			</view>
			<view class="right" @click="submitForm(3)">
				完成添加
			</view>
		</view>

		<uni-popup ref="popup">
			<view class="pop-info">
				<view class="title">
					<view>分类</view>
					<image src="/static/image/icon2/xx.png" @click="closeType"></image>
				</view>
				<view class="btn" @click="openInput(1)">
					+新增分类
				</view>
				<scroll-view scroll-y="true" style="height: 350px;">
					<radio-group @change="typeChange">
						<label class="radio-lab" v-for="(item, index) in typeRange" :key="item.value">
							<view class="radio-items">{{item.title}}
								<radio :value="index" color="#2979ff" :checked="index === typeIndex" />
							</view>
						</label>
					</radio-group>
				</scroll-view>

			</view>
		</uni-popup>



		<uni-popup ref="norms" :is-mask-click="false">
			<view class="pop-info">
				<view class="title">
					<view>商品规格</view>
					<image src="/static/image/icon2/xx.png" @click="confirmNorms(0)"></image>
				</view>
				<view class="btn" @click="openInput(2)">
					+新增商品规格
				</view>
				<scroll-view scroll-y="true" style="height: 350px;">
					<radio-group @change="normsChange">
						<view class="radio-lab" v-for="(item, index) in normsRange" :key="index">
							<label class="radio-items">{{item.title}}
								<radio :value="index" :checked="normsIndex==index" color="#2979ff" />
							</label>
							<view class="check-boks" v-show="normsIndex==index">
								<view :class="['check-boks-lable',att.checked?'active':'']"
									@click="normsCheck(index,idx)" v-for="att,idx in item.childs" :key="idx">
									{{att.title}}
								</view>
								<view class="add-attr" @click="openInput(3,index)">+</view>
							</view>
						</view>
					</radio-group>
				</scroll-view>
				<view class="btn-confrm" @click="confirmNorms(1)">
					确定
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="attribute" :is-mask-click="false">
			<view class="pop-info">
				<view class="title">
					<view>商品属性</view>
					<image src="/static/image/icon2/xx.png" @click="confirmAttribute(0)"></image>
				</view>
				<view class="btn" @click="openInput(4)">
					+新增商品属性
				</view>
				<scroll-view scroll-y="true" style="height: 350px;">
					<view>
						<view class="radio-lab" v-for="(item, index) in attributeRange" :key="index">
							<view class="radio-items" @click="attributeChange(index)">
								<view class="name">
									{{item.title}}
								</view>
								<image class="box-img" :src="item.checked?'/static/check.png':'/static/check-no.png'"
									mode="widthFix">
								</image>
							</view>
							<view class="check-boks">
								<view :class="['check-boks-lable',att.checked?'active':'']"
									@click="attributeCheck(index,idx)" v-for="att,idx in item.childs" :key="idx">
									{{att.title}}
								</view>
								<view class="add-attr" @click="openInput(5,index)">+</view>
							</view>
						</view>
					</view>
				</scroll-view>
				<view class="btn-confrm" @click="confirmAttribute(1)">
					确定
				</view>
			</view>
		</uni-popup>


		<uni-popup ref="typeInput" type="dialog">
			<uni-popup-dialog mode="input" :title="popTitle" @confirm="confirm(inputValue)">
				<uni-easyinput v-model="inputValue" focus :placeholder="popPh"></uni-easyinput>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	const app = getApp();
	export default {
		data() {
			return {
				formData: {
					category_id: "", //分类ID
					key: uni.getStorageSync('userKey'),
					original: "",
					price: "",
					show_image: "",
					specificationList: "", //规格列表
					subtitle: "",
					title: ""
				},
				typeRange: [],
				typeIndex: null,
				normsRange: [],
				normsIndex: null,
				attributeRange: [],
				crrNoIndex: null,
				popTitle: "",
				popPh: "",
				inputType: 1,
				busId: null,
				memberDiscount: null,
				crrGoods: null,
				inputValue: null,
				picServiceUrl: app.globalData.picServiceUrl,
			}
		},
		computed: {
			checkedAttribute: function() {
				let arr = this.attributeRange.filter(item => item.checked)
				return arr;
			}
		},
		onLoad(e) {
			this.busId = e.id;
			if (e.memberDiscount) {
				console.log(e.memberDiscount)
				this.memberDiscount = e.memberDiscount;
			}

			if (e.goods) {
				let json = e.goods;
				if (json) {
					this.crrGoods = JSON.parse(json);
					console.log(this.crrGoods)
					this.formData = {
						category_id: this.crrGoods.categoryId, //分类ID
						key: uni.getStorageSync('userKey'),
						original: this.crrGoods.original / 100,
						price: this.crrGoods.price / 100,
						show_image: this.crrGoods.showImage,
						specificationList: this.crrGoods.specificationList, //规格列表
						subtitle: this.crrGoods.subtitle,
						title: this.crrGoods.title
					};
					let arr = this.crrGoods.specificationList;
					let nRange = [];
					let aRange = [];
					for (let i in arr) {
						let obj = {
							checked: true,
							title: arr[i].title,
							id: arr[i].id,
							childs: []
						}
						let sum = 0;
						for (let j in arr[i].childs) {
							obj.childs.push({
								checked: true,
								id: arr[i].childs[j].id,
								title: arr[i].childs[j].title,
								repetory: arr[i].childs[j].repetory,
								price: arr[i].childs[j].price / 100,
								original: arr[i].childs[j].original / 100
							})
							sum += arr[i].childs[j].original;
						}
						if (sum) {
							nRange.push(obj);
						} else {
							aRange.push(obj);
						}

					}
					this.normsRange = nRange;
					this.normsIndex = nRange.length ? 0 : null;
					this.attributeRange = aRange;
				}
			}
		},
		onShow() {
			this.getType();
		},
		methods: {
			attributeCheck(index, idx) {
				this.attributeRange[index].childs[idx].checked = !this.attributeRange[index].childs[idx]
					.checked
			},
			attributeChange(index) {
				this.attributeRange[index].checked = !this.attributeRange[index].checked;
			},
			openAttribute() {
				this.$refs.attribute.open('bottom')
			},
			confirmAttribute(type) {
				let arr = [];
				for (let i in this.attributeRange) {
					if (this.attributeRange[i].checked) {
						let arr = this.attributeRange[i].childs.filter(item => item.checked);
						if (!arr.length) {
							if (type) {
								return uni.showToast({
									title: "请添加并选择属性选项",
									icon: "none"
								})
							} else {
								this.attributeRange[i].checked = false;
							}
						}
					}

				}
				this.$refs.attribute.close();
			},
			delPriceType(indx) {
				this.normsRange[this.normsIndex].childs[indx].checked = false;
				let arr = this.normsRange[this.normsIndex].childs.filter(item => item.checked);
				if (!arr.length) {
					this.normsIndex = null;
					this.formData.price = null;
					this.formData.original = null;
				}
			},
			normsCheck(index, idx) {
				this.normsRange[index].childs[idx].checked = !this.normsRange[index].childs[idx]
					.checked
			},
			normsChange(e) {
				this.normsIndex = e.detail.value;
			},
			openNorms() {
				this.$refs.norms.open('bottom')
			},
			confirmNorms(type) {
				let arr = [];
				if (this.normsIndex != null) {
					arr = this.normsRange[this.normsIndex].childs.filter(item => item.checked);
				} else {
					return this.$refs.norms.close();
				}
				if (arr.length) {
					this.$refs.norms.close();
				} else {
					if (type) {
						uni.showToast({
							title: "请添加并选择规格选项",
							icon: "none"
						})
					} else {
						this.$refs.norms.close();
						this.normsIndex = null;
						this.formData.price = null;
						this.formData.original = null;
					}
				}
			},
			typeOpen() {
				this.$refs.popup.open('bottom')
			},
			typeChange(e) {
				this.typeIndex = e.detail.value;
				this.closeType();
			},
			closeType() {
				this.$refs.popup.close();
			},
			openInput(type, index) {
				this.inputValue = "";
				if (type == 1) {
					this.popTitle = "新增分类";
					this.popPh = "请输入分类名称"
				} else if (type == 2) {
					this.popTitle = "新增规格";
					this.popPh = "请输入规格名称"
				} else if (type == 3) {
					this.popTitle = "新增规格选项";
					this.popPh = "请输入规格选项名称";
					this.crrNoIndex = index;
				} else if (type == 4) {
					this.popTitle = "新增属性";
					this.popPh = "请输入属性名称";
					this.crrNoIndex = index;
				} else if (type == 5) {
					this.popTitle = "新增属性选项";
					this.popPh = "请输入属性选项名称";
					this.crrNoIndex = index;
				}
				this.inputType = type;
				this.$refs.typeInput.open()
			},
			confirm(e) {
				if (!e) {
					return;
				}
				if (this.inputType == 1) {
					this.addType(e);
				} else if (this.inputType == 2) {
					this.normsRange.push({
						title: e,
						childs: []
					})
				} else if (this.inputType == 3) {
					for (let i in this.normsRange[this.crrNoIndex].childs) {
						if (this.normsRange[this.crrNoIndex].childs[i].title == e) {
							return uni.showToast({
								title: "选项名称重复",
								icon: "none"
							})
						}
					}
					this.normsRange[this.crrNoIndex].childs.push({
						title: e,
						checked: true,
						original: null,
						repetory: null,
						price: null,
					})
				} else if (this.inputType == 4) {
					if (e) {
						this.attributeRange.push({
							title: e,
							checked: true,
							childs: []
						})
						console.log(123)
					}
				} else if (this.inputType == 5) {
					for (let i in this.attributeRange[this.crrNoIndex].childs) {
						if (this.attributeRange[this.crrNoIndex].childs[i].title == e) {
							return uni.showToast({
								title: "选项名称重复",
								icon: "none"
							})
						}
					}
					this.attributeRange[this.crrNoIndex].childs.push({
						title: e,
						checked: true,
						original: 0,
						repetory: 9999,
						price: 0,
					})
				}
			},
			selectPic(res) {
				console.log(res)
				uni.uploadFile({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/doUploadOfflineBusinessGoodsShowImage', //仅为示例，非真实的接口地址
					filePath: res.tempFilePaths[0],
					name: 'file',
					success: (uploadFileRes) => {
						this.formData.show_image = uploadFileRes.data;
					}
				});
			},
			getType() {
				uni.request({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/getOfflineBusinessGoodsCategoryList',
					method: 'POST',
					data: {
						offlineBusinessId: this.busId
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						this.typeRange = res.data.data;
						if (this.crrGoods && this.crrGoods.categoryId) {
							for (let i in this.typeRange) {
								if (this.typeRange[i].id == this.crrGoods.categoryId) {
									this.typeIndex = i;
								}
							}
						}
					}
				});
			},
			submitForm(type) {
				if (type == 0) { //删除
					this.delGood();
				} else {
					this.submitReq(type);
				}
			},
			addType(title) {
				let url;
				uni.request({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/addOfflineBusinessCategory',
					method: 'POST',
					data: {
						key: uni.getStorageSync('userKey'),
						offline_business_id: this.busId,
						title: title
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						this.getType();
					}
				});
			},
			delGood() {
				uni.request({
					url: app.globalData.serviceUrl +
						'/UserMiniProgramController/deleteOfflineBusinessGoods',
					method: 'POST',
					data: {
						key: uni.getStorageSync('userKey'),
						offline_business_id: this.busId,
						goods_id: this.crrGoods.id
					},
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.showToast({
							title: res.data.notice,
							icon: "none"
						})
						if (res.data.state == 1) {
							uni.navigateBack({
								delta: 1
							})
						}
					}
				});
			},
			submitReq(type) {
				if (!this.typeIndex) {
					return uni.showToast({
						icon: "none",
						title: "请选择分类"
					})
				}
				let fData = JSON.parse(JSON.stringify(this.formData));
				fData.category_id = this.typeRange[this.typeIndex].id;
				fData.offline_business_id = this.busId;

				fData.repetory = 9999;

				let json = [];
				if (this.normsIndex != null) {
					let obj = {
						title: this.normsRange[this.normsIndex].title,
						id: this.normsRange[this.normsIndex].id,
						childs: []
					}
					let range = this.normsRange[this.normsIndex].childs;
					for (let j in range) {
						if (range[j].checked) {
							if (range[j].original <= 0) {
								return uni.showToast({
									icon: "none",
									title: "请填写原价"
								})
							}

							if (this.memberDiscount) {
								range[j].price = range[j].original * this.memberDiscount;
							} else {
								if (range[j].price <= 0) {
									return uni.showToast({
										icon: "none",
										title: "请填写底价"
									})
								}
							}
							let _price = parseFloat(range[j].price * 100).toFixed(0);
							let _original = parseFloat(range[j].original * 100).toFixed(0);
							obj.childs.push({
								id: range[j].id,
								title: range[j].title,
								price: _price,
								original: _original,
								repetory: range[j].repetory == null ? 9999 : range[j].repetory
							})
						}
					}
					fData.price = 0;
					fData.original = 0;
					json.push(obj);
				} else {


					if (fData.original <= 0) {
						return uni.showToast({
							icon: "none",
							title: "请填写原价"
						})
					}

					if (this.memberDiscount) {
						fData.price = fData.original * this.memberDiscount;
					} else {
						if (fData.price <= 0) {
							return uni.showToast({
								icon: "none",
								title: "请填写底价"
							})
						}
					}
					fData.price = parseFloat(fData.price * 100).toFixed(2);
					fData.original = parseFloat(fData.original * 100).toFixed(2);
				}

				for (let i in this.checkedAttribute) {
					let range = this.checkedAttribute[i].childs;
					let obj = {
						title: this.checkedAttribute[i].title,
						id: this.checkedAttribute[i].id,
						childs: []
					}
					for (let j in range) {
						if (range[j].checked) {
							obj.childs.push({
								id: range[j].id,
								title: range[j].title,
								price: 0,
								original: 0,
								repetory: range[j].repetory,
							})
						}
					}
					json.push(obj);
				}

				fData.specificationList = JSON.stringify(json);
				let url = '/UserMiniProgramController/addOfflineBusinessGoods';
				if (type == 1) {
					url = '/UserMiniProgramController/updateOfflineBusinessGoods';
					fData.goods_id = this.crrGoods.id;
				}
				uni.request({
					url: app.globalData.serviceUrl + url,
					method: 'POST',
					data: fData,
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.showToast({
							title: res.data.notice,
							icon: "none"
						})
						if (res.data.state == 1) {
							if (type == 2) {
								this.formData.show_image = null;
								this.formData.category_id = null;
								this.formData.original = null;
								this.formData.price = null;
								this.formData.title = null;
								this.formData.specificationList = [];
								this.normsIndex = null;
								this.$refs.filePicker.clearFiles();
								for (let i in this.attributeRange) {
									this.attributeRange[i].checked = false;
								}
							} else if (type == 3 || type == 1) {
								uni.navigateBack({
									delta: 1
								})
							}
						}

					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.hide-pad {
		.uni-forms-item__inner {
			padding-bottom: 10px;
			padding-top: 10px;
		}
	}

	.img-pic {
		width: 95px;
		height: 95px;
	}

	.guige-info {
		font-size: 14px;

		.title {
			margin-bottom: 5px;
		}

		.price-info {
			display: flex;
			background: #eee;
			color: #333;
			padding: 10px;
			margin-bottom: 10px;
			position: relative;

			.del {
				position: absolute;
				right: -15px;
				top: -15px;
				padding: 10px;
				z-index: 9;

				image {
					width: 16px;
					height: 16px;
				}
			}

			.price-info-title {
				flex: 0 0 100px;
				overflow: hidden;
			}

			input {
				flex: 1 1 0;
				border-bottom: 1px solid #DCDFE6;
				color: #333;
			}
		}
	}

	.sub-bt-btn {
		display: flex;
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #fff;
		z-index: 10;

		view {
			margin: 10px;
			line-height: 40px;
			flex: 1 1 0;
			text-align: center;
			color: #fff;
		}

		.left {
			background: #999;
		}

		.right {
			background: #333;
		}
	}

	.pop-info {
		background: #fff;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
		padding: 15px;

		.title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 20px;
			border-bottom: 1px solid #E2E2E2;
			padding-bottom: 10px;
			margin-bottom: 10px;

			image {
				width: 20px;
				height: 20px;
			}
		}

		.btn {
			color: #2979ff;
			line-height: 50px;
			border-bottom: 1px solid #E2E2E2;
		}

		.radio-lab {
			border-bottom: 1px solid #E2E2E2;

			.radio-items {
				line-height: 50px;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.box-img {
					width: 30px;
					height: 30px;
				}
			}

			.check-boks {
				margin-bottom: 10px;

				.check-boks-lable {
					margin-right: 15px;
					display: inline-block;
					padding: 0 10px;
					height: 30px;
					line-height: 30px;
					border: 1px solid #333;
					border-radius: 2px;
				}

				.active {
					background: rgba(41, 121, 255, 0.2);
					border: 1px solid #2979ff;
					color: #2979ff;
				}

				.add-attr {
					display: inline-block;
					width: 30px;
					height: 30px;
					text-align: center;
					line-height: 30px;
					border: 1px solid #999;
					font-size: 25px;
					border-radius: 2px;
					position: relative;
					top: 3px;
				}
			}
		}

		.btn-confrm {
			width: 120px;
			line-height: 35px;
			text-align: center;
			margin: 10px auto;
			background: #333;
			color: #fff;
		}
	}

	.page-bg {
		background: rgba(242, 243, 248, 1);
		height: 100vh;
		padding-top: 20px;
		padding-bottom: 100px;
	}

	.page-form {
		border-radius: 10px;
		padding: 10px;
		margin: 0 10px;
		background: #fff;
	}

	.select-pic {
		height: 80px;
		width: 80px;
		border: 1px solid #e5e5e5;
		text-align: center;
		line-height: 80px;
		border-radius: 5px;
	}

	.select-info {
		height: 36px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.row {
			width: 18px;
			height: 18px;
		}

		.podct {
			color: #999;
		}
	}
</style>
